package cn.jsp.dao;

import cn.jsp.jdbc.GeneralRowProcessor;
import cn.jsp.jdbc.RowProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Repository
public class BaseDao <T>{
    @Autowired
    DataSource dataSource;
    public List<T> query(String sql, RowProcessor<T> rowProcessor, Object...params){
        List<T> stus=new ArrayList<>();
        try (
                Connection connection =dataSource.getConnection();
                PreparedStatement preparedStatement=connection.prepareStatement( sql);
                ResultSet resultSet=preparedStatement.executeQuery())
        {
            while(resultSet.next()){
                T stu =rowProcessor.process(resultSet);
                stus.add(stu);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return stus;
    }
    public List<T> find(String sql, Class<T> target, Object...params){
        List<T> stus=new ArrayList<>();
        RowProcessor<T> rowProcessor =new GeneralRowProcessor<>(target);
        try (
                Connection connection =dataSource.getConnection();
                PreparedStatement preparedStatement=connection.prepareStatement( sql);
                ResultSet resultSet=preparedStatement.executeQuery())
        {
            while(resultSet.next()){
                T stu =rowProcessor.process(resultSet);
                stus.add(stu);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return stus;
    }

}